package cc.avatar.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
 * Temporal Property 时效属性，时间段，工具类
 * 非程序员第6期有一篇文章详细介绍了Temporal Pattern - 时效模式
 */
public class TemporalCollection {

	private Map<Date,Object> contents = new HashMap<Date,Object>();

	//时间界碑
	private List<Date> milestoneCache;

	public Object get(Date when) {
		/** returns the value that was effective on the given date */
		Iterator<Date> it = milestones().iterator();
		while (it.hasNext()) {
			Date thisDate = it.next();
			if (thisDate.before(when) || thisDate.equals(when))
				return contents.get(thisDate);
		}
		return null;
		//milestones().find{it->it.before(when)||t.equals(when)}
	}

	public void put(Date at, Object item) {
		/** the item is valid from the supplied date onwards */
		contents.put(at, item);
		clearMilestoneCache();
	}

	//returns these keys in reverse order
	private List<Date> milestones() {
		/** a list of all the dates where the value changed, returned in order
		 latest first */
		if (milestoneCache == null)
			calculateMilestones();
		return milestoneCache;
	}

	private void clearMilestoneCache() {
		milestoneCache = null;
	}

	private void calculateMilestones() {
		milestoneCache = new ArrayList<Date>(contents.size());
		milestoneCache.addAll(contents.keySet());
		Collections.sort(milestoneCache, Collections.reverseOrder());
	}

}